#include "animationplayerwidget.h"
#include "gameObjects/visualobject.h"
#include "globaldata.h"
#include "application.h"

AnimationPlayerWidget::AnimationPlayerWidget(QWidget *parent)
	: QWidget(parent)
	, m_nCurrentAnimationFrame(0)
{
	ui.setupUi(this);
	connect(this, &AnimationPlayerWidget::currentAnimationFrameChanged, 
		Application::instance().globalData(), &GlobalData::setCurrentAnimationFrame);
	m_timer.setInterval(1000/30);
	connect(&m_timer, &QTimer::timeout, this, &AnimationPlayerWidget::onTimer);
	connect(ui.pushButtonPlayStop, &QPushButton::clicked, 
		this, &AnimationPlayerWidget::onToggleAnimationPlaying);
}

void AnimationPlayerWidget::onDocumentChanged( QPointer<Document> doc )
{
	m_nCurrentAnimationFrame = 0;
	m_timer.stop();
}

void AnimationPlayerWidget::setVisualObject( QPointer<AbstractGameObject> visualObject )
{
	m_visualObject = visualObject;
	m_nCurrentAnimationFrame = 0;
	m_timer.stop();
	emit currentAnimationFrameChanged(m_nCurrentAnimationFrame);
}

void AnimationPlayerWidget::onTimer()
{
	QPointer<VisualObject> vo = qobject_cast<VisualObject*>(m_visualObject);
	Q_ASSERT(vo);

	++m_nCurrentAnimationFrame;
	if(m_nCurrentAnimationFrame > vo->numFrames() - 1)
	{
		m_nCurrentAnimationFrame = 0;
	}

	emit currentAnimationFrameChanged(m_nCurrentAnimationFrame);
}

void AnimationPlayerWidget::onToggleAnimationPlaying()
{
	if(m_timer.isActive())
	{
		m_timer.stop();
	}
	else
	{
		m_timer.start();
	}
}
